<?php
/**
 * Created by PhpStorm.
 * User: SUNHUATAO
 * Desc: 前台新闻中心控制器
 */
namespace App\Modules\Home\Http\Controllers;

use App\Http\Controllers\BasicController;
use App\Modules\Manage\Model\NewsModel;
use App\Modules\Manage\Model\NewsCategoryModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class NewsController extends BasicController
{
    public function __construct()
    {
        parent::__construct();
        $this->initTheme('home');
    }

    /**@Desc 新闻列表
     * @param Request $request
     * @param null $typeID
     * @return mixed
     */
    public function newsList(Request $request, $typeID = null)
    {
        $merge = $request->all();
        if($typeID){
            $list = NewsModel::leftJoin('news_category','news.cat_id','=','news_category.id')->where('news.cat_id',$typeID)
                ->select('news.id','news.title','news.updated_at','news_category.cate_name')
                ->orderBy('news.created_at','desc')->paginate(8);
        }else{
            $list = NewsModel::leftJoin('news_category','news.cat_id','=','news_category.id')
                ->select('news.id','news.title','news.updated_at','news_category.cate_name')
                ->orderBy('news.created_at','desc')->paginate(8);
        }
        $listArr = $list->toArray()['data'];
        $data = [
            'merge' => $merge,
            'list'  => $list,
            'listArr'=> $listArr
        ];

        $data['type'] = self::newsType();
        $this->theme->setTitle('新闻中心');
        return $this->theme->scope('home/newsCenter',$data)->render();
    }

    /**
     * @desc 新闻分类
     * @return null
     */
    static function newsType($limit = 0)
    {
        $type = NewsCategoryModel::where('pid',1)->select('id','cate_name')->orderBy('display_order','desc');
        if($limit !=0){
        $type->limit($limit);
        }
        $type = $type->get();
        if(!empty($type)){
            $type=$type->toArray();
        }
        return $type;
    }

    /**
     * @desc 首页新闻
     * @param int $limit
     * @return mixed
     */
    static function newsIndex($limit = 6)
    {
        $news = NewsModel::select('id','title','content')->orderBy('created_at','desc')->limit($limit)->get()->toArray();
        return $news;
    }

    /**@desc 新闻详情
     * @param $id
     * @return mixed
     */
    public function newsInfo($id)
    {
        $data['type'] = self::newsType();
        $data['info'] = NewsModel::where('id',$id)->select('title','content','updated_at','keywords','description')->first()->toArray();
        $this->theme->setTitle('新闻详情');
        $this->theme->setKeywords($data['info']['keywords']);
        $this->theme->setDescription($data['info']['description']);
        return $this->theme->scope('home/newsInfo',$data)->render();
    }


}